package io.github.jyrmc.deploy.utils

import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import java.io.ByteArrayOutputStream

/**
 * 命令执行
 *
 * @author jy
 * @since 2023/5/16 9:58
 **/
object CommandLineUtils {

    /**
     * 执行命令行
     */
    fun exec(host: String, port: Int = 22, username: String = "root", password: String, commandLine: String): String {
        var session: Session? = null
        var channel: ChannelExec? = null

        val result: String
        try {
            session = JSch().getSession(username, host, port)
            session.setPassword(password)
            session.setConfig("StrictHostKeyChecking", "no")
            session.connect()
//            channel = session.openChannel("shell") as ChannelExec
            channel = session.openChannel("exec") as ChannelExec
            channel.setCommand(commandLine)
            val responseStream = ByteArrayOutputStream()
            channel.outputStream = responseStream
            channel.connect()
            while (channel.isConnected) {
                Thread.sleep(100)
            }
            result = responseStream.toString()
        } finally {
            session?.disconnect()
            channel?.disconnect()
        }

        return result
    }

    /**
     * 执行命令行
     */
    fun execNoWait(session: Session, commandLine: String) {
        var channel: ChannelExec? = null
        try {
            channel = session.openChannel("exec") as ChannelExec
            channel.setCommand(commandLine)
            channel.connect()
            while (channel.isConnected) {
                Thread.sleep(1000)
            }
        } finally {
            channel?.disconnect()
            session.disconnect()
        }
    }
}